/**
 * 
 */
package com.ieasy.module.system.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ieasy.basic.dao.IBaseDao;
import com.ieasy.basic.exception.ServiceException;
import com.ieasy.basic.model.Msg;
import com.ieasy.basic.model.SystemContext;
import com.ieasy.basic.util.BeanUtils;
import com.ieasy.module.common.web.servlet.WebContextUtil;
import com.ieasy.module.system.entity.DeptHistoryEntity;
import com.ieasy.module.system.web.form.DeptHistoryForm;

/**
 * @author 杨浩泉
 *
 */
@Service @Transactional
public class DeptHistoryService implements IDeptHistoryService {
	
	@Inject
	private IBaseDao<DeptHistoryEntity> basedaoPostionHistroy ;
	
	@Override
	public Msg add(DeptHistoryForm form) {
		DeptHistoryEntity entity = new DeptHistoryEntity() ;
		BeanUtils.copyNotNullProperties(form, entity) ;
		entity.setCreateName(WebContextUtil.getCurrentUser().getUser().getEmp_name()) ;
		entity.setCreated(new Date()) ;
		
		this.basedaoPostionHistroy.add(entity) ;
		return new Msg(true, "添加成功！");
	}
	

	@Override
	public Msg delete(DeptHistoryForm form) {
		try {
			if(null != form.getId() && !"".equals(form.getId())) {
				this.basedaoPostionHistroy.executeSQL("delete from ieasy_sys_dept_history where id=?", form.getId()) ;
				return new Msg(true, "删除成功！") ;
			}
		} catch (Exception e) {
			return new Msg(false, "删除失败！") ;
		}
		return null;
	}
	
	@Override
	public DeptHistoryForm get(DeptHistoryForm form) {
		DeptHistoryEntity entity = this.basedaoPostionHistroy.load(DeptHistoryEntity.class, form.getId()) ;
		BeanUtils.copyNotNullProperties(entity, form) ;
		return form ;
	}

	@Override
	public List<DeptHistoryForm> list(DeptHistoryForm form) {
		SystemContext.setSort("t.endDate") ; SystemContext.setOrder("desc") ;
		try {
			return this.find(form) ;
		} catch (Exception e) {
			throw new ServiceException("加载信息异常", e) ;
		}
	}

	private List<DeptHistoryForm> find(DeptHistoryForm form) {
		Map<String, Object> alias = new HashMap<String, Object>();
		String sql = "select " +
					 "t.* " +
				 	 "from ieasy_sys_dept_history t " +
				 	 "where 1=1 ";
		sql = addWhere(sql, form, alias) ;
		return this.basedaoPostionHistroy.listSQL(sql, alias, DeptHistoryForm.class, false) ;
	}

	private String addWhere(String hql, DeptHistoryForm form, Map<String, Object> params) {
		if (form.getPersonId() != null && !"".equals(form.getPersonId())) {
			hql += " and t.personId=:personId";
			params.put("personId", form.getPersonId());
		}
		return hql;
	}

	

	
}
